import React, { useState, useEffect } from 'react';
import { SERVER_URL_OBJ } from '@/../config/urlConfig';
import { downLoadFile } from '../../services';
import { message } from 'antd';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import { useFullscreen } from 'ahooks';
import './index.less';

const PreviewContent: React.FC<IPreviewContentProps> = (props) => {
  const { CLIENT_ENV } = process.env;
  const [url, setUrl] = useState<string>();
  const [loading, setLaoding] = useState<boolean>(false);
  const [isFullscreen, { enterFullscreen, exitFullscreen }] = useFullscreen(() =>
    document.getElementById('settlementManagePreview'),
  );
  useEffect(() => {
    if (props.name && props.path) {
      if (props.name.indexOf('.xls') > -1) {
        SERVER_URL_OBJ;
        const env = !CLIENT_ENV || CLIENT_ENV === 'dev' ? 'release' : CLIENT_ENV;
        // @ts-ignore
        const downloadUrl = `${SERVER_URL_OBJ[env]}/annex/annex/downLoadFile/${props.path}`;
        const url = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
          downloadUrl,
        )}`;
        setUrl(url);
      }

      if (props.name.indexOf('.pdf') > -1) {
        setLaoding(true);
        downLoadFile(props.path)
          .then((res: any) => {
            if (res && !res.statusCode && res.size > 66) {
              const bolb = new Blob([res], { type: 'application/pdf;chartset=UTF-8' });
              setUrl(URL.createObjectURL(bolb));
            } else {
              message.error('预览文件下载失败');
            }
          })
          .finally(() => setLaoding(false));
      }
    } else {
      setUrl('');
    }
  }, [props.name, props.path]);

  return (
    <div className="preview-content" id="settlementManagePreview">
      <div className="title">
        预览
        {url && (
          <div>
            {isFullscreen ? (
              <FullscreenExitOutlined onClick={() => exitFullscreen()} />
            ) : (
              <FullscreenOutlined onClick={() => enterFullscreen()} />
            )}
          </div>
        )}
      </div>
      <div className="iframe-box">
        {url && <iframe src={url} frameBorder={0} className="iframe" />}
      </div>
    </div>
  );
};

interface IPreviewContentProps {
  name: string;
  path: string;
}

export default PreviewContent;
